<?php
/*
 * Copyright 2010 Johannes M. Schmitt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Provides some static methods which are frequently used.
 * 
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class GoogleClosureUtil
{
	/**
	 * Used for caching the path to the base.js file
	 * @var string
	 */
	private static $baseFilePath;
	
	/**
	 * Returns the path to the Google Closure Library base.js file
	 * 
	 * @throws RuntimeException if a base.js file is not found, or
	 *											 		if multiple base.js files are found.
	 * @return string
	 */
	public static function getBaseFile()
	{
		if (self::$baseFilePath === null)
		{
	    // find the path to the base.js file
	    $files = sfFinder::type('file')
	    			->name('base.js')
	    			->follow_link()
	    			->exec(array(get_called_class(), 'checkIfBase'))
	    			->in(sfConfig::get('sf_web_dir'));
	    if (count($files) === 0)
	    	throw new RuntimeException('Could not locate base.js file.');
	    else if (count($files) > 1)
	    	throw new RuntimeException('Multiple base.js files found.');
	    	
	    self::$baseFilePath = $files[0];
		}
		
		return self::$baseFilePath;
	}
	
	/**
	 * This is only used internally to perform a simple check whether the
	 * given base.js file is indeed the Google Closure base file.
	 * 
	 * @param string $dir
	 * @param string $entry
	 * @return boolean
	 */
	public static function checkIfBase($dir, $entry)
  {
  	$content = file_get_contents($dir.'/'.$entry);
  	return strpos($content, 'var goog = goog || {};') !== false;
  }
}